/**
 * Copyright 2022 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef NNACL_FP32_GRAD_ACTIVATION_GRAD_AVX512_H_
#define NNACL_FP32_GRAD_ACTIVATION_GRAD_AVX512_H_

#include "nnacl/intrinsics/ms_simd_instructions.h"
#include "nnacl/intrinsics/ms_simd_avx512_instructions.h"

#ifdef __cplusplus
extern "C" {
#endif
#pragma GCC push_options
#pragma GCC target("avx512f")
#define MS_SIMD_INSTRUCTION MS_SIMD_AVX512_INSTRUCTION
#define BLOCK_NUM 16
#define MS_SIMD_AVX512

static inline int ShrinkGradAVX512(int index, const float *src0, const float *src1,
                                               int length, float *dst, float lambd) {
    SIMD_F32 pos_lamdb_v = SIMD_MOV_F32(lambd);
    SIMD_F32 neg_lamdb_v = SIMD_MOV_F32(-lambd);

    for (int block_max_size = length - BLOCK_NUM + 1; index < block_max_size; index += BLOCK_NUM) {
        SIMD_F32 src0_t = SIMD_LD_F32(src0 + index);
        SIMD_F32 src1_t = SIMD_LD_F32(src1 + index);

        SIMD_MASK mask0 = SIMD_CMPLE_F32(src1_t, pos_lamdb_v);
        SIMD_MASK mask1 = SIMD_CMPLE_F32(neg_lamdb_v, src1_t);
        SIMD_MASK mask = SIMD_AND_MASK(mask0, mask1);

        SIMD_ST_F32(dst + index, SIMD_BLEND_F32(src0_t, SIMD_MOV_F32(0.0f), mask));
    }
    return index;
}

#undef MS_SIMD_INSTRUCTION
#undef BLOCK_NUM
#pragma GCC pop_options
#undef MS_SIMD_AVX512
#ifdef __cplusplus
}
#endif
#endif
